/**
 * JSON格式化工具，提供JSON结构的分层展示功能
 */
export class JsonFormatter {
    /**
     * 判断字符串是否为有效的JSON
     */
    public static isValidJson(str: string): boolean {
        try {
            JSON.parse(str);
            return true;
        } catch {
            return false;
        }
    }

    /**
     * 将JSON字符串格式化为可折叠的分层视图
     */
    public static formatJsonToHtml(jsonString: string): string {
        try {
            const jsonObj = JSON.parse(jsonString);
            return this.createJsonTree(jsonObj);
        } catch (error) {
            return `<div class="json-error">无效的JSON格式: ${error}</div>`;
        }
    }

    /**
     * 创建JSON树形结构HTML
     */
    private static createJsonTree(obj: any, key?: string, level: number = 0): string {
        const type = this.getType(obj);
        
        if (type === 'object') {
            const keys = Object.keys(obj);
            if (keys.length === 0) {
                return `<span class="json-object">{}</span>`;
            }

            let html = `<div class="json-object-container">`;
            html += `<span class="json-toggle" onclick="toggleJsonNode(this)">${key ? `"${key}": ` : ''}{</span>`;
            html += `<div class="json-children" style="display: none;">`;
            
            keys.forEach((k: string, index: number) => {
                const isLast = index === keys.length - 1;
                html += `<div class="json-property">${this.createJsonTree(obj[k], k, level + 1)}${isLast ? '' : ','}</div>`;
            });
            
            html += `</div>`;
            html += `<span class="json-bracket">}</span>`;
            html += `</div>`;
            
            return html;
        } else if (type === 'array') {
            if (obj.length === 0) {
                return `<span class="json-array">[]</span>`;
            }

            let html = `<div class="json-array-container">`;
            html += `<span class="json-toggle" onclick="toggleJsonNode(this)">${key ? `"${key}": ` : ''}[</span>`;
            html += `<div class="json-children" style="display: none;">`;
            
            obj.forEach((item: any, index: number) => {
                const isLast = index === obj.length - 1;
                html += `<div class="json-item">${this.createJsonTree(item, undefined, level + 1)}${isLast ? '' : ','}</div>`;
            });
            
            html += `</div>`;
            html += `<span class="json-bracket">]</span>`;
            html += `</div>`;
            
            return html;
        } else {
            return this.formatPrimitive(obj, key);
        }
    }

    /**
     * 格式化原始值
     */
    private static formatPrimitive(value: any, key?: string): string {
        const type = this.getType(value);
        let formattedValue = '';
        
        switch (type) {
            case 'string':
                formattedValue = `<span class="json-string">"${value}"</span>`;
                break;
            case 'number':
                formattedValue = `<span class="json-number">${value}</span>`;
                break;
            case 'boolean':
                formattedValue = `<span class="json-boolean">${value}</span>`;
                break;
            case 'null':
                formattedValue = `<span class="json-null">null</span>`;
                break;
            default:
                formattedValue = `<span class="json-unknown">${String(value)}</span>`;
        }
        
        return key ? `<span class="json-key">"${key}": </span>${formattedValue}` : formattedValue;
    }

    /**
     * 获取值的类型
     */
    private static getType(value: any): string {
        if (value === null) return 'null';
        if (Array.isArray(value)) return 'array';
        return typeof value;
    }

    /**
     * 获取JSON格式化所需的CSS样式
     */
    public static getJsonStyles(): string {
        return `
            <style>
                .json-container {
                    font-family: 'Consolas', 'Monaco', monospace;
                    font-size: 12px;
                    line-height: 1.4;
                    padding: 10px;
                    background-color: var(--vscode-editor-background);
                    color: var(--vscode-editor-foreground);
                    border: 1px solid var(--vscode-editorWidget-border);
                    border-radius: 3px;
                    max-height: 400px;
                    overflow-y: auto;
                }
                
                .json-toggle {
                    cursor: pointer;
                    user-select: none;
                    color: var(--vscode-editor-foreground);
                }
                
                .json-toggle:hover {
                    text-decoration: underline;
                }
                
                .json-toggle::before {
                    content: '▶';
                    display: inline-block;
                    width: 12px;
                    transition: transform 0.2s;
                    color: var(--vscode-editor-foreground);
                }
                
                .json-toggle.expanded::before {
                    transform: rotate(90deg);
                }
                
                .json-children {
                    margin-left: 20px;
                    border-left: 1px solid var(--vscode-editorWidget-border);
                    padding-left: 10px;
                }
                
                .json-key {
                    color: var(--vscode-symbolIcon-propertyForeground);
                    font-weight: bold;
                }
                
                .json-string {
                    color: var(--vscode-symbolIcon-stringForeground);
                }
                
                .json-number {
                    color: var(--vscode-symbolIcon-numberForeground);
                }
                
                .json-boolean {
                    color: var(--vscode-symbolIcon-booleanForeground);
                }
                
                .json-null {
                    color: var(--vscode-symbolIcon-nullForeground);
                    font-style: italic;
                }
                
                .json-bracket {
                    color: var(--vscode-editor-foreground);
                }
                
                .json-error {
                    color: var(--vscode-errorForeground);
                    padding: 10px;
                    background-color: var(--vscode-inputValidation-errorBackground);
                    border: 1px solid var(--vscode-inputValidation-errorBorder);
                    border-radius: 3px;
                }
                
                .json-property, .json-item {
                    margin: 2px 0;
                }
                
                .json-object-container, .json-array-container {
                    margin: 2px 0;
                }
            </style>
        `;
    }

    /**
     * 获取JSON交互所需的JavaScript
     */
    public static getJsonScripts(): string {
        return `
            <script>
                function toggleJsonNode(element) {
                    const container = element.parentElement;
                    const children = container.querySelector('.json-children');
                    const isExpanded = element.classList.contains('expanded');
                    
                    if (isExpanded) {
                        children.style.display = 'none';
                        element.classList.remove('expanded');
                    } else {
                        children.style.display = 'block';
                        element.classList.add('expanded');
                    }
                }
                
                // 展开所有节点
                function expandAllJson() {
                    document.querySelectorAll('.json-toggle').forEach(toggle => {
                        const container = toggle.parentElement;
                        const children = container.querySelector('.json-children');
                        children.style.display = 'block';
                        toggle.classList.add('expanded');
                    });
                }
                
                // 折叠所有节点
                function collapseAllJson() {
                    document.querySelectorAll('.json-toggle').forEach(toggle => {
                        const container = toggle.parentElement;
                        const children = container.querySelector('.json-children');
                        children.style.display = 'none';
                        toggle.classList.remove('expanded');
                    });
                }
            </script>
        `;
    }
}
